/*!
 * 文章导入模块
 * @author Sherlock 
 * @return check 检查远程文章地址的有效性
 * @return doRemotoRequest 获取远程文章信息
 * @return submit 提交文档到h2进行解析
 */
require( './style.less' );

define( [
  'require',
  'jquery',
  'message',
  'bootstrap',
  'bootstrap-select',
  'h2Api',
  'api',
  'jqueryFrom',
  'constants',
  'bigwe_component'
], function( require, $, msg ) {
  var reg = /^((http|https):\/\/mp\.weixin\.qq\.com\/s)(.*)/;
  var showTime = msg.showTime;
  var apis = require( 'api' );
  var c = require( 'constants' );
  var components = require( 'bigwe_component' );
  var articleImport = {
    hosts: [
      'www.toutiao.com',
      'mp.weixin.qq.com',
      'baijia.baidu.com',
      '163.com',
      'www.yidianzixun.com',
      'www.jianshu.com'
    ],
    hostsCheck: function( url ) {
      var isInHosts = false;
      $.each( this.hosts, function( k, v ) {
        if ( url.indexOf( v ) > -1 ) {
          isInHosts = true;
          return false;
        }
      } );
      return isInHosts;
    },
    check: function( url ) {
      var urlObj = null;
      // 微信文章正则
      if ( /^\s*$/.test( url ) ) {
        return msg.showWarning( "先赐予我文章链接哦~", showTime );
      } else {
        try {
          urlObj = new URL( url );
        } catch ( e ) {
          return msg.showWarning( '请输入正确的url地址', showTime );
        }
        if ( this.hostsCheck( urlObj.hostname ) ) {
          if ( reg.test( url ) ) {
            var param = url.match( reg )[ 3 ] || '';
            if ( !param ) {
              return msg.showWarning( "参数错误，请复制完整的链接", showTime );
            } else {
              if ( param.indexOf( '?' ) != 0 && param.indexOf( '/' ) != 0 ) {
                return msg.showWarning( "参数错误，请复制完整的链接", showTime );
              }
            }
          }
        } else {
          return msg.showWarning( '暂不支持您提交的地址源:-(', msg.showTime );
        }

      }
      return true;
    },
    doRemotoRequest: function( url, success ) {
      if ( reg.test( url ) ) {
        var param = url.match( reg )[ 3 ] || '';
        if ( param.indexOf( '?' ) == 0 ) {
          url = url.replace( /((http|https):\/\/mp\.weixin\.qq\.com\/s\?)(.)/, '$1f=json&$3' );
        } else if ( param.indexOf( '/' ) == 0 ) {
          url += '?f=json';
        }
      }

      msg.show( "努力抓取中(ง •̀_•́)ง" );
      return $.ajax( {
        url: apis.EDIT_TEXT.CAPTURE_SRC,
        type: 'POST',
        dataType: 'json',
        data: {
          url: url
        },
        success: function( data ) {
          if ( data.ret === 0 ) {
            if ( $.isFunction( success ) ) {
              success.call( window, data.data.content, url );
            }
          } else {
            msg.showWarning( data.msg || '文章导入失败', msg.showTime );
          }
        }
      } );
    },
    submit: function( successCall ) {
      var wordUploadUrl = require( 'h2Api' ).WORD_IMPORT + '?ak=' + c.applicationKey;
      window.uploadConfig_uploadSize = 5;
      var _this = this;
      _this.action = wordUploadUrl,
        _this.enctype = 'multipart/form-data',
        _this.method = 'POST';
      msg.show( "文档玩儿命上传中，可能耗时较长，请耐心等待" );

      $( _this ).ajaxSubmit( {
        type: 'post',
        url: wordUploadUrl,
        success: function( data ) {
          msg.hide();

          var jsonData = typeof data === 'string' ? $.parseJSON( data ) : data;

          if ( jsonData.ret === 0 ) {
            _this.reset();
            $.isFunction( successCall ) && successCall.call( this, jsonData.data );
          } else {
            msg.showWarning( jsonData.msg || '文档解析失败，可能包含了无法解析的格式', msg.showTime );
          }
        },
        error: function() {
          _this.reset();
          msg.showWarning( '服务器发生异常，文档解析失败:(', msg.showTime );
        }
      } );


    }
  }

  function strFIlter( str ) {
    return str.replace( /&rdquo;/g, '”' )
      .replace( /&ldquo;/g, '“' )
      .replace( /&lsquo;/g, '‘' )
      .replace( /&rsquo;/g, '’' )
      .replace( /&middot;/g, '·' )
      .replace( /&mdash;/g, '—' );
  }

  $( function() {
    var ai = $( '#article_import.article_import_modal' );

    function afterSubmit() {
      ai.modal( 'hide' );
      $( 'form', ai ).each( function() {
        this.reset();
      } );
      $( '#input_url', ai ).val( '' );
    }
    var docType = {
      word: function() {
        var dsFrom = document.getElementById( 'data_sub_frm' );
        if ( !$( '#doc_file', dsFrom ).val() ) {
          return msg.showWarning( "请先选择一个文档", showTime );
        }
        articleImport.submit.call( dsFrom, function( data ) {
          var matchStr = data.match( /<body[\s\S]*<\/body>/g ) || [ '' ];
          data = strFIlter( matchStr[ 0 ] === '' ? data : matchStr[ 0 ] );
          if ( c.pageID === 'TLM016' ) {
            if ( typeof current_editor !== 'undefined' ) {

              if ( current_editor.getContent() ) {
                components.confirm( '系统检测到有正文内容，是否直接覆盖？\n（取消将直接插入内容）', function() {
                  current_editor.setContent( data )
                }, function() {
                  current_editor.execCommand( 'inserthtml', data )
                } );
              } else {
                current_editor.setContent( data )
              }

            }
          } else {
            $( '#doc_text', ai ).val( escape( data ) ).parent()[ 0 ].submit()
          }
          afterSubmit();
        } );
      },
      wechat: function() {
        var url = $( '#input_url', ai ).val();
        if ( articleImport.check( url ) ) {
          var forwardUrl = '/edit_text?edit_type=1&remotoUrl=' + escape( url );
          if ( c.pageID === 'TLM016' ) {
            //location.href = forwardUrl;
            if ( typeof current_editor !== 'undefined' ) {
              articleImport.doRemotoRequest( url, function( data ) {
                if ( typeof current_editor.options.remotoHtmlCallback == 'function' ) {
                  if ( !current_editor.options.remotoHtmlCallback.apply( current_editor, arguments ) ) {
                    msg.hide();
                  } else {
                    msg.show( "抓取成功(ˇ▽ˇ)(ˇ▽ˇ)(ˇ▽ˇ)，尽情编辑吧~", msg.showTime );
                  }
                }
              } );
            }
          } else {
            window.open( forwardUrl, 'remotoArt' );
          }
          afterSubmit();
        }
      }
    };


    articleImport.$selector = ai;
    $( '.selectpicker', ai ).selectpicker();

    ai.on( 'click', '.js_browse_file', function() {
      $( '#doc_file', ai ).trigger( 'click' );
    } ).on( 'change', '#import_type', function() {
      var type = $( this ).val();
      $( '[data-show]', ai ).addClass( 'hide' );
      $( '[data-show="' + type + '"]', ai ).removeClass( 'hide' );
    } ).on( 'click', '.js_OK', function() {
      docType[ $( '#import_type', ai ).val() ]();
    } ).on( 'change', '#doc_file', function() {
      var fileName = $( this ).val();
      fileName = fileName.substr( fileName.lastIndexOf( '\\' ) + 1, fileName.length - 1 );
      $( '.sub_file_name', ai ).text( fileName ).prop( 'title', fileName );
    } ).on( 'reset', '#data_sub_frm', function() {
      var text = '点击“浏览”选择文件';
      $( '.sub_file_name', ai ).text( text ).prop( 'title', text );
    } );

    $( document ).on( 'click', '.js_article_import', function() {
      ai.modal( 'show' );
    } );
  } );


  return articleImport;
} );
